package com.shiliao.app.manager;

import android.text.TextUtils;

import com.shiliao.app.ShiliaoApplication;
import com.shiliao.app.manager.entity.UserEntity;
import com.shiliao.app.utils.YMServerUtil;
import com.yimei.framework.network.ICallBack;
import com.yimei.framework.network.OkhttpManager;
import com.yimei.framework.util.LogUtil;
import com.yimei.framework.util.ParseHelper;
import com.yimei.framework.util.StringUtils;
import com.yimei.framework.util.SystemUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 公共参数处理类
 * Created by yjl on 2017/7/13.
 */

public class NetworkManager {

    private static String mURL = YMServerUtil.getServerUrl();//"http://192.168.11.152:8012";

    private NetworkManager() {

    }

    public static void loadDataByGet(String action, final ICallBack mCallBack) throws Exception {
        if (!TextUtils.isEmpty(mURL) && !TextUtils.isEmpty(action)) {

            String url = addParamGet(mURL + action);
            OkhttpManager.getInstance().loadDataByGet(url, new ICallBack() {
                @Override
                public void onSuccess(int statusCode, Object result) {
                    chargeResultCorrect(statusCode, mCallBack, result);
                }

                @Override
                public void onFail(int statusCode, Object result) {
                    LogUtil.e("onFail statusCode:" + statusCode);
                    LogUtil.e("onFail result:" + result);
                    try {
                        if (result != null && !TextUtils.isEmpty(result.toString())) {
                            String state = ParseHelper.getString(result.toString(), "state");
                            if (state != null && "1003".equals(state)) {
                                YMUserManager.Logout();
                            }
                        }
                    } catch (Exception e) {
                    }
                    if (mCallBack != null) {
                        mCallBack.onFail(statusCode, result);
                    }
                }
            });
        }
    }

    public static void loadDataByGet(String action, Map params, final ICallBack mCallBack) throws Exception {
        if (!TextUtils.isEmpty(mURL) && !TextUtils.isEmpty(action)) {
            String url = addParamGet(mURL + action);
            OkhttpManager.getInstance().loadDataByGet(url, params, new ICallBack() {
                @Override
                public void onSuccess(int statusCode, Object result) {
                    chargeResultCorrect(statusCode, mCallBack, result);
                }

                @Override
                public void onFail(int statusCode, Object result) {
                    LogUtil.e("onFail statusCode:" + statusCode);
                    LogUtil.e("onFail result:" + result);
                    try {
                        if (result != null && !TextUtils.isEmpty(result.toString())) {
                            String state = ParseHelper.getString(result.toString(), "state");
                            if (state != null && "1003".equals(state)) {
                                YMUserManager.Logout();
                            }
                        }
                    } catch (Exception e) {
                    }
                    if (mCallBack != null) {
                        mCallBack.onFail(statusCode, result);
                    }
                }
            });
        }
    }

    public static void loadDataByPost(String action, String json, final ICallBack mCallBack) throws Exception {
        if (!StringUtils.isEmpty(action)) {
            OkhttpManager.getInstance().loadDataByPost(mURL + action, addParamJsonString(json), new ICallBack() {
                @Override
                public void onSuccess(int statusCode, Object result) {
                    chargeResultCorrect(statusCode, mCallBack, result);
                }

                @Override
                public void onFail(int statusCode, Object result) {
                    LogUtil.e("onFail statusCode:" + statusCode);
                    LogUtil.e("onFail result:" + result);
                    try {
                        if (result != null && !TextUtils.isEmpty(result.toString())) {
                            String state = ParseHelper.getString(result.toString(), "state");
                            if (state != null && "1003".equals(state)) {
                                YMUserManager.Logout();
                            }
                        }
                    } catch (Exception e) {
                    }
                    if (mCallBack != null) {
                        mCallBack.onFail(statusCode, result);
                    }
                }
            });
        }
    }

    /**
     * post方式不添加额外参数
     *
     * @param action
     * @param mCallBack
     * @throws Exception
     */
    public static void loadDataByPost(final String action, final ICallBack mCallBack) throws Exception {
        loadDataByPost(action, new HashMap(), mCallBack);
    }

    public static void loadDataByPost(final String action, Map param, final ICallBack mCallBack) throws Exception {
        if (!StringUtils.isEmpty(action)) {
            //TODO @Yzq 后续需要改成OkhttpManager.getInstance().loadDataByPost(mURL+action, param, new ICallBack()
            OkhttpManager.getInstance().loadDataByPost(mURL + action, param, new ICallBack() {
                @Override
                public void onSuccess(int statusCode, Object result) {
                    try {
                        chargeResultCorrect(statusCode, mCallBack, result);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFail(int statusCode, Object result) {
                    LogUtil.e("onFail:" + mURL + action + "   statusCode:" + statusCode);
                    LogUtil.e("onFail result:" + result);
                    try {
                        if (result != null && !TextUtils.isEmpty(result.toString())) {
                            String state = ParseHelper.getString(result.toString(), "state");
                            if (state != null && "1003".equals(state)) {
                                YMUserManager.Logout();
                            }
                        }
                    } catch (Exception e) {
                    }
                    if (mCallBack != null) {
                        mCallBack.onFail(statusCode, result);
                    }
                }
            });
        }
    }

    /**
     * 判断返回值是否正确
     *
     * @param statusCode
     * @param mCallBack
     * @param result
     */
    private static void chargeResultCorrect(int statusCode, ICallBack mCallBack, Object result) {
        LogUtil.d(result.toString());
        if (mCallBack == null) {
            LogUtil.e("fail: mCallBack is null!");
            return;
        }
//        try {
//            //判断是否要强制登录
//            if (result != null) {
//                String state = ParseHelper.getString(result.toString(), "state");
//                if (state != null && "1003".equals(state)) {
//                    YMUserManager.Logout();
//                } else if (state != null && "0".equals(state)) {
//                    mCallBack.onFail(Integer.valueOf(state), result);
//                    return;
//                }
//            }
//        } catch (Exception e) {
//        }
        try {
            //判断返回值是否正确
            JSONObject jsonObject = new JSONObject(result.toString());
            if (jsonObject != null) {
//                LogUtil.e("yzq", jsonObject + "===" + statusCode + "==" + result.toString());
                LogUtil.e("yzq", jsonObject+"" );
                mCallBack.onSuccess(statusCode, result);
            } else {
                LogUtil.e("yzq", jsonObject + "===" + statusCode + "==" + result.toString());
                mCallBack.onFail(statusCode, result);
            }
        } catch (JSONException e) {
            mCallBack.onFail(statusCode, result);
            e.printStackTrace();
        }
    }

    public static String addParamGet(String url) {
        StringBuilder strbu = new StringBuilder(url);
        if (!TextUtils.isEmpty(url)) {
            if (!url.contains("?")) {
                strbu.append("?");
            } else {
                strbu.append("&");
            }
            strbu.append("api_request_way=1");
            String device_no = SystemUtils.getUserDeviceID();
            strbu.append("&device_no=").append(device_no);
            if (YMUserManager.getUserLoginState(ShiliaoApplication.getInstance())) {
                UserEntity userEntity = YMUserManager.getUesrInfo(ShiliaoApplication.getInstance());
                if (userEntity != null) {
                    strbu.append("&user_id=").append(userEntity.getmUserId());
                    strbu.append("&access_token=").append(userEntity.getmAccessToken());
                }
            }

        }
        return strbu.toString();
    }

    public static Map addParamPost(Map map) {
        if (map == null) {
            map = new HashMap();
        }
        map.put("api_request_way", 1);
        String device_no = SystemUtils.getUserDeviceID();
        map.put("device_no", device_no);
        if (YMUserManager.getUserLoginState(ShiliaoApplication.getInstance())) {
            UserEntity userEntity = YMUserManager.getUesrInfo(ShiliaoApplication.getInstance());
            if (userEntity != null) {
                map.put("user_id", userEntity.getmUserId());
                map.put("access_token", userEntity.getmAccessToken());
            }
        }
        return map;
    }

//    public static Map addParamPostRaw(Map map) {
//        if (map == null) {
//            map = new HashMap();
//        }
//        map.put("user_id", 1);
//
//        return map;
//    }

    private static String addParamJsonString(String json) {

        try {
            JSONObject jsonObject;
            if (StringUtils.isNotEmpty(json)) {
                jsonObject = new JSONObject(json);
            } else {
                jsonObject = new JSONObject();
            }
            jsonObject.put("api_request_way", 1);
            String device_no = SystemUtils.getUserDeviceID();
            jsonObject.put("device_no", device_no);
            if (YMUserManager.getUserLoginState(ShiliaoApplication.getInstance())) {
                UserEntity userEntity = YMUserManager.getUesrInfo(ShiliaoApplication.getInstance());
                if (userEntity != null) {
                    jsonObject.put("user_id", userEntity.getmUserId());
                    jsonObject.put("access_token", userEntity.getmAccessToken());
                }
            }
            return jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }


    public static void loadRequsetByRaw(final String url, Map map, final ICallBack iCallBack) {
        JSONObject jsonObject = TransMapToJson(map);
        try {
            if (!StringUtils.isEmpty(url)) {
                OkhttpManager.getInstance().loadRequsetByRaw(mURL + url, jsonObject.toString(), new ICallBack() {
                    @Override
                    public void onSuccess(int statusCode, Object result) {
                        chargeResultCorrect(statusCode, iCallBack, result);
                    }

                    @Override
                    public void onFail(int statusCode, Object result) {
                        LogUtil.e("yzq", "onFail:" + mURL + url + "   statusCode:" + statusCode);
                        LogUtil.e("yzq", "onFail result:" + result);
//                        try {
//                            if (result != null && !TextUtils.isEmpty(result.toString())) {
//                                String state = ParseHelper.getString(result.toString(), "state");
//                                if (state != null && "1003".equals(state)) {
//                                    YMUserManager.Logout();
//                                }
//                            }
//                        } catch (Exception e) {
//                        }
                        if (iCallBack != null) {
                            iCallBack.onFail(statusCode, result);
                        }
                    }
                });
            }

        } catch (IOException e) {
            iCallBack.onFail(500, e.getMessage());
            e.printStackTrace();
        }
    }

    public static JSONObject TransMapToJson(Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject();
        for (Object k : map.keySet()) {
            try {
                jsonObject.put(String.valueOf(k), map.get(k));
            } catch (Exception e) {

            }
        }

        return jsonObject;
    }

    /**
     * 上传图片
     *
     * @param action
     * @param param     其他参数，包括图片参数地址
     * @param picKey    图片参数
     * @param mCallBack
     * @throws Exception
     */
    public void postPic(final String action, Map param, String picKey, final ICallBack mCallBack) throws Exception {
        if (!StringUtils.isEmpty(action)) {
            param = addParamPost(param);
            LogUtil.e("onSuccess:" + mURL + action + "\n param:" + param + "\n picKey:" + picKey);
            OkhttpManager.getInstance().postPic(mURL + action, param, picKey, new ICallBack() {
                @Override
                public void onSuccess(int statusCode, Object result) {
                    LogUtil.e("onSuccess:" + mURL + action
                            + "   statusCode:" + statusCode + "    result:" + result);
                    try {
                        chargeResultCorrect(statusCode, mCallBack, result);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFail(final int statusCode, final Object result) {
                    LogUtil.e("onFail:" + mURL + action
                            + "   statusCode:" + statusCode + "    result:" + result);
                    try {
                        if (mCallBack != null) {
                            mCallBack.onFail(statusCode, result);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public void clearImageCache(String path) {
        OkhttpManager.getInstance().clearImageCache(path);
    }
}
